package com.yswee.framework.widget.switchtab;

import com.yswee.framework.R;
import com.yswee.framework.utils.UnitUtils;
import com.yswee.framework.widget.layoutview.MHorizontalScrollView;
import com.yswee.framework.widget.layoutview.MLinearLayout;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.viewpager.widget.ViewPager;

public class SwitchTabBar extends MHorizontalScrollView<String[]> implements ISwitchTabBar {

	protected String[] childTitle;
	protected TextView[] childviewList;

	protected boolean scrollable;
	protected boolean titleStretch;
	protected int currentPosition = 0;
	protected float currentPositionOffset = 0f;
	protected Paint indicatorPaint;
	protected Paint underlinePaint;
	protected Paint splitPaint;
	
	protected boolean drawIndicator;
	protected int backgroundResId = 0;
	protected int indicatorHeight = 0;
	protected int indicatorColor = 0;
	protected int underlineHeight = 0;
	protected int underlineColor = 0;
	protected int splitWidth = 0;
	protected int splitColor = 0;
	protected int titleFontSize = 0;
	
	protected ISwitchTabBarAction switchTabBarAction;
	protected InnerSwitchTabBar contentView;

	protected final PageListener pageListener = new PageListener();
	
	public void setSwitchTabBarAction(ISwitchTabBarAction l) {
		switchTabBarAction = l;
	}
	
	@Override
	public int getTabCount() {
		return childTitle != null ? childTitle.length : 0;
	}

	public SwitchTabBar(Context context) {
		super(context);
	}
	
	@SuppressWarnings("deprecation")
	public SwitchTabBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		drawIndicator = true;
		scrollable = true;
		titleStretch = true;

		backgroundResId = R.color.widget_switchbar_bg;
		indicatorHeight = (int) getResources().getDimension(R.dimen.widget_switchbar_indicator_height);
		indicatorColor = getResources().getColor(R.color.widget_switchbar_indicator);
		underlineHeight = (int) getResources().getDimension(R.dimen.widget_switchbar_underline_height);
		underlineColor = getResources().getColor(R.color.widget_switchbar_line);
		splitWidth = (int) getResources().getDimension(R.dimen.widget_switchbar_split_width);
		splitColor = getResources().getColor(R.color.widget_switchbar_split);
		titleFontSize = (int) getResources().getDimension(R.dimen.widget_switchbar_fontsize);

		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwitchTabBar);

		backgroundResId = a.getResourceId(R.styleable.SwitchTabBar_SwitchTabBar_background, backgroundResId);
		drawIndicator = a.getBoolean(R.styleable.SwitchTabBar_SwitchTabBar_drawIndicator, drawIndicator);
		indicatorColor = a.getColor(R.styleable.SwitchTabBar_SwitchTabBar_indicatorColor, indicatorColor);
		underlineColor = a.getColor(R.styleable.SwitchTabBar_SwitchTabBar_underlineColor, underlineColor);
		splitColor = a.getColor(R.styleable.SwitchTabBar_SwitchTabBar_splitColor, splitColor);
		indicatorHeight = (int) a.getDimension(R.styleable.SwitchTabBar_SwitchTabBar_indicatorHeight, indicatorHeight);
		underlineHeight = (int) a.getDimension(R.styleable.SwitchTabBar_SwitchTabBar_underlineHeight, underlineHeight);
		splitWidth = (int) a.getDimension(R.styleable.SwitchTabBar_SwitchTabBar_splitWidth, splitWidth);
		titleFontSize = (int) a.getDimension(R.styleable.SwitchTabBar_SwitchTabBar_title_fontsize, titleFontSize);
		scrollable = a.getBoolean(R.styleable.SwitchTabBar_SwitchTabBar_scrollable, scrollable);
		titleStretch = a.getBoolean(R.styleable.SwitchTabBar_SwitchTabBar_title_stretch, titleStretch);
		
		int dataResId = a.getResourceId(R.styleable.SwitchTabBar_SwitchTabBar_datasource, 0);
		if(dataResId != 0) {
			childTitle = getResources().getStringArray(dataResId);
		}

		a.recycle();
	}
	
	@Override
	protected void initializeLayout(Context context) {
		super.initializeLayout(context);
//		hideFadingEdge();
		setWillNotDraw(false);
		setHorizontalScrollBarEnabled(false);
		setBackgroundResource(backgroundResId);
		contentView = new InnerSwitchTabBar(mContext);
		addView(contentView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if(underlineHeight > 0) {
			final int height = getHeight();
			// draw under line
			if(underlinePaint == null) {
				underlinePaint = new Paint();
				underlinePaint.setAntiAlias(true);
				underlinePaint.setStyle(Style.FILL);
				underlinePaint.setColor(underlineColor);
			}
			canvas.drawRect(0, height - underlineHeight, getWidth(), height, underlinePaint);
		}
		contentView.invalidate();
	}

	@Override
	protected void onApplyData() {
		contentView.setDataSource(mDataItem);
		if (switchTabBarAction != null && switchTabBarAction.getTabView() != null) {
			switchTabBarAction.getTabView().setOnPageChangeListener(pageListener);
			switchTabBarAction.getTabView().initializeView();
		}
	}
	
	@Override
	public void setDataSource(String[] t) {
		if (t == null) {
			if (childTitle != null) {
				t = childTitle;
			}
		} else {
			childTitle = t;
		}
		super.setDataSource(t);
	}

	@Override
	public void setTabIndex(int index) {
		if(childviewList != null) {
			for(int i = 0; i < childviewList.length; i++) {
				if(childviewList[i] != null) {
		    		if(i == index) {
		    			focusChildView(i);
		    		} else {
		    			unfocusChildView(i);
		    		}
				}
	    	}
		}
	}
	
	@SuppressWarnings("deprecation")
	protected void focusChildView(int index) {
		childviewList[index].setTextColor(getResources().getColor(R.color.widget_switchbar_focus_fg));
		TextPaint tp = childviewList[index].getPaint(); 
		tp.setFakeBoldText(true); 
	}
    
	@SuppressWarnings("deprecation")
	protected void unfocusChildView(int index) {
		childviewList[index].setTextColor(getResources().getColor(R.color.widget_switchbar_unfocus_fg));
		TextPaint tp = childviewList[index].getPaint(); 
		tp.setFakeBoldText(false); 
	}
	
	protected void recalcScrollBar() {
		try {
			if (switchTabBarAction == null || switchTabBarAction.getTabView() == null) {
				return;
			}
			View currentTab = contentView.getChildAt(switchTabBarAction.getTabView().getCurrentItem());
			int lineLeft = currentTab.getLeft();
			int lineRight = currentTab.getRight();
			int screenLeft = getScrollX();
			int screenRight = getScrollX() + getWidth();
			int scrollx = -1;
			if (lineRight >= screenRight) {
				scrollx = lineRight - getWidth();
			} else if (lineLeft <= screenLeft) {
				scrollx = lineLeft;
			}
			if (scrollx >= 0) {
				scrollTo(scrollx, 0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected int getTitleBarTextViewLayoutResId() {
		return R.layout.widget_switchbar_textview;
	}

	protected class PageListener implements ViewPager.OnPageChangeListener {
		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			currentPosition = position;
			currentPositionOffset = positionOffset;
			recalcScrollBar();
			invalidate();
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			
		}

		@Override
		public void onPageSelected(int position) {
			currentPosition = position;
		}
	}
	
	public class InnerSwitchTabBar extends MLinearLayout<String[]> {
		
		public InnerSwitchTabBar(Context context) {
			super(context);
		}
		
		@Override
		protected void initializeLayout(Context context) {
			super.initializeLayout(context);
			setOrientation(HORIZONTAL);
			setWillNotDraw(false);
		}
		
		@Override
		protected void onLayout(boolean changed, int l, int t, int r, int b) {
			super.onLayout(changed, l, t, r, b);
			if (changed) {
				notifyDataSetChanged();
			}
		}
		
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			if (isInEditMode()) {
				return;
			}
			if(drawIndicator) {
				final int height = getHeight();
				// draw indicator line
				if(indicatorPaint == null) {
					indicatorPaint = new Paint();
					indicatorPaint.setAntiAlias(true);
					indicatorPaint.setStyle(Style.FILL);
					indicatorPaint.setColor(indicatorColor);
				}
				float lineLeft = 0;
				float lineRight = 0;
				if (!scrollable && !titleStretch) {
					View currentTab = getChildAt(currentPosition);
					if (currentTab == null) {
						return;
					}
					View currentTabChild = ((ViewGroup) currentTab).getChildAt(0);
					lineLeft = currentTab.getLeft() + currentTabChild.getLeft();
					lineRight = currentTab.getLeft() + currentTabChild.getRight();
					// if there is an offset, start interpolating left and right coordinates between current and next tab
					if (currentPositionOffset > 0f && currentPosition < getChildCount() - 1) {
			
						View nextTab = getChildAt(currentPosition + 1);
						View nextTabChild = ((ViewGroup) nextTab).getChildAt(0);
						final float nextTabLeft = nextTab.getLeft() + nextTabChild.getLeft();
						final float nextTabRight = nextTab.getLeft() + nextTabChild.getRight();
			
						lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
						lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
					}
				} else {
					View currentTab = getChildAt(currentPosition);
					if (currentTab == null) {
						return;
					}
					lineLeft = currentTab.getLeft();
					lineRight = currentTab.getRight();
					// if there is an offset, start interpolating left and right coordinates between current and next tab
					if (currentPositionOffset > 0f && currentPosition < getChildCount() - 1) {
			
						View nextTab = getChildAt(currentPosition + 1);
						final float nextTabLeft = nextTab.getLeft();
						final float nextTabRight = nextTab.getRight();
			
						lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
						lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
					}
				}
				canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, indicatorPaint);
			}
			if (splitWidth > 0) {
				final int height = getHeight();
				// draw indicator line
				if(splitPaint == null) {
					splitPaint = new Paint();
					splitPaint.setAntiAlias(true);
					splitPaint.setStyle(Style.FILL);
					splitPaint.setColor(splitColor);
				}
				for (int i = 0; i < getChildCount(); i++) {
					View view = getChildAt(i);
					LinearLayout.LayoutParams params = (LayoutParams) view.getLayoutParams();
					canvas.drawLine(view.getRight() + params.rightMargin - splitWidth / 2, UnitUtils.dip2pix(mContext, 10), 
							view.getRight() + params.rightMargin + splitWidth / 2, height - UnitUtils.dip2pix(mContext, 10), splitPaint);
				}
			}
		}

		@Override
		protected void onApplyData() {
			if(childTitle != null) {
				int parentWidth = 0;
				if (!scrollable) {
					parentWidth = SwitchTabBar.this.getMeasuredWidth() - 
							SwitchTabBar.this.getPaddingLeft() -
							SwitchTabBar.this.getPaddingRight();
				}
				int childPadding = (int) (scrollable || !titleStretch ? 
						getResources().getDimension(R.dimen.widget_switchbar_textview_padding) : 0);
				int childMargin = (int) (scrollable ? getResources().getDimension(
						R.dimen.widget_switchbar_textview_margin) : 0);
				LayoutParams childGroupParam = new LayoutParams((scrollable ? LayoutParams.WRAP_CONTENT : 
						parentWidth / childTitle.length), LayoutParams.MATCH_PARENT);
				childGroupParam.setMargins(childMargin, 0, childMargin, 0);
				LayoutParams childParam = new LayoutParams((!scrollable && titleStretch ? LayoutParams.MATCH_PARENT : 
						LayoutParams.WRAP_CONTENT), LayoutParams.MATCH_PARENT);
				LayoutInflater inflater = LayoutInflater.from(mContext);
				childviewList = new TextView[childTitle.length];
				for(int i = 0; i < childTitle.length; i++) {
					childviewList[i] = null;
					if (i < getChildCount()) {
						ViewGroup group = (ViewGroup) getChildAt(i);
		            	group.setLayoutParams(childGroupParam);
						childviewList[i] = (TextView) group.getChildAt(0);
		            	childviewList[i].setPadding(childPadding, 0, childPadding, indicatorHeight);
		            	childviewList[i].setLayoutParams(childParam);
					} else {
						LinearLayout titleContainer = new LinearLayout(mContext);
						titleContainer.setGravity(Gravity.CENTER);
						childviewList[i] = (TextView) inflater.inflate(getTitleBarTextViewLayoutResId(), titleContainer, false);
						childviewList[i].setTextSize(TypedValue.COMPLEX_UNIT_PX, titleFontSize);
		            	childviewList[i].setPadding(childPadding, 0, childPadding, indicatorHeight);
						titleContainer.addView(childviewList[i], childParam);
						addView(titleContainer, childGroupParam);
					}
	            	childviewList[i].setText(childTitle[i]);
	            	childviewList[i].setTag(i);
	            	childviewList[i].setOnClickListener(new OnClickListener() {
	            		public void onClick(View v) {
	            			int index = Integer.parseInt(v.getTag().toString());
	            			int oldindex = -1;
	            			if(switchTabBarAction != null && switchTabBarAction.getTabView() != null) {
	            				oldindex = switchTabBarAction.getTabView().getCurrentItem();
	            			}
	            			if (oldindex != index) {
		            			if(switchTabBarAction != null && switchTabBarAction.getTabView() != null) {
		            				switchTabBarAction.getTabView().onTabChanged(index, true);
		            			} else {
		            				setTabIndex(index);
		            			}
	            			}
	            		}
	            	});
				}
				for (int i = childTitle.length; i < getChildCount(); i++) {
					getChildAt(i).setVisibility(View.GONE);
				}
			} else {
				for (int i = 0; i < getChildCount(); i++) {
					getChildAt(i).setVisibility(View.GONE);
				}
			}
			SwitchTabBar.this.requestLayout();
		}
	}

	public interface ISwitchTabBarAction {
		ISwitchTabView getTabView();
	}

}